<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Admin;
use app\common\model\Banner;
use app\common\model\Company;
use app\common\model\factory\Category;
use app\common\model\Goods;
use app\common\model\User;
use app\common\model\wash\Order as ModelWashOrder;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function ceshi()
    {
        // $dd = User::commission(29.90, 0, '20240307164133bd1d062', 138);
    }
    /**
     * 门店列表
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (GET)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="lat", type="integer", required=true, sample="", description="lat")
     * @ApiParams (name="lng", type="integer", required=true, sample="", description="lng")
     * @ApiParams (name="city", type="integer", required=true, sample="", description="lng")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function shop_list()
    {
        $param = request()->param();
        extract($param);
        $user = new User;
        if (isset($city) && $city) {
            $user->whereLike('city', '%' . $city . '%');
        }

        $list =  $user->field(['id,nickname,avatar,address,lat,lng,company_id', self::distanceSql($lat ?? 0, $lng ?? 0)])->where('role', 'shop')->where('status', 'normal')->order('distance ASC')->select();
        foreach ($list as $key => $data) {
            $com = Admin::get($data['company_id']);
            if ($com) {
                $data->city = Admin::get($com->pid);
            }
        }
        $this->success('', $list);
    }
    /**
     * 附近门店
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="lat", type="integer", required=true, sample="", description="lat")
     * @ApiParams (name="lng", type="integer", required=true, sample="", description="lng")
     * @ApiParams (name="city", type="integer", required=true, sample="", description="lng")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function nearshop()
    {
        $param = request()->param();
        extract($param);
        $user = new User;
        if (isset($city) && $city) {
            $user->whereLike('city', '%' . $city . '%');
        }
        $data = $user->field(['id,nickname,avatar,address,lat,lng,company_id', self::distanceSql($lat ?? 0, $lng ?? 0)])->where('role', 'shop')->where('status', 'normal')->order('distance ASC')->find();
        $com = Admin::get($data['company_id']);
        if ($com) {
            $data->city = Admin::get($com->pid);
        }
        $this->success('', $data);
    }

    /**
     * 获取排序sql
     * @param $latitude 29.596078
     * @param $longitude 105.064033
     * @return mixed
     */
    private static function distanceSql($latitude, $longitude)
    {
        $field = "(round(6378.137 * 2 * asin(sqrt(pow(sin(((lat * pi()) / 180 - ({$latitude} * pi()) / 180) / 2), 2) + cos(({$latitude} * pi()) / 180) * cos((lat * pi()) / 180) * pow(sin(((lng * pi()) / 180 - ({$longitude} * pi()) / 180) / 2), 2))),2)) AS distance";
        return $field;
    }
    /**
     * 首页
     *
     */
    public function index()
    {
        $param = request()->param();
        extract($param);
        $data['category'] = isset($company_id) && $company_id ? Category::all(['admin_id' => $company_id]) : [];
        $data['banner'] = Banner::all();
        $data['goodsList'] = Goods::all(['state' => 2]);
        $user = $this->auth->getUser();
        foreach ($data['goodsList'] as $v) {
            if (isset($user['group_id']) && $user['group_id'] == 2) {
                if (isset($v->item[0])) {
                    $v->current_price = $v->item[0]->inside_price;
                }
            } else {
                if (isset($v->item[0])) {
                    $v->current_price = $v->item[0]->price;
                }
            }
        }
        $data['order_list'] = ModelWashOrder::with(['user' => function ($q) {
            $q->withField('id,nickname,avatar');
        }])->where('order.status', 'in', ['1', '2', '3', '4'])->field('order.id,total_fee as total_money,order.createtime')->order('order.id desc')->limit(20)->select();
        $data['news'] = Company::where('state', '2')->order('id desc')->limit(2)->field('id,title,image,createtime')->select();
        $this->success('', $data);
    }

    /**
     * 资讯列表
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="page", type="integer", required=true, sample="", description="页码")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function newslist()
    {
        $res = Company::order('id desc')->field('id,title,image,createtime')->paginate(10);
        $this->responseMsg(0, $res);
    }

    /**
     * 资讯详情
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function newsdetail()
    {
        $rej = $this->validate(
            $this->request->post(),
            [
                'id'  => 'require|gt:0',
            ]
        );

        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $res = Company::get($this->request->post('id'));
        if (!$res) {
            $this->responseMsg(1005, [], '未找到该记录');
        }
        $this->responseMsg(0, $res);
    }
}
